package com.auditlog.listener;

import cn.hutool.core.bean.BeanUtil;
import com.auditlog.datasource.context.ConnectionContext;
import com.auditlog.datasource.context.ContextHolder;
import com.auditlog.datasource.context.ExecutionContext;
import com.auditlog.listener.AuditLogEventBus;
import com.auditlog.listener.ContextChangeEvent;
import com.auditlog.handler.OperationHandlerRegistry;
import com.auditlog.handler.meta.UserOperationHandler;

/**
 *
 * @author Zhiyang.Zhang
 * @date 2022/12/4 12:40
 * @version 1.0
 */
public class EventPublisher {
    public static void publishRecordChangeEvent() {
        ConnectionContext connectionContext = ContextHolder.getConnectionContext();
        UserOperationHandler userOperationHandler = OperationHandlerRegistry.getInstance().getOperationUserHandler();
        ExecutionContext executeContext = ContextHolder.getExecuteContext();
        executeContext.setUserId(userOperationHandler.userId());
        executeContext.setUserName(userOperationHandler.userName());
        executeContext.setMetaData(userOperationHandler.metaData());
        BeanUtil.copyProperties(connectionContext,executeContext);
        AuditLogEventBus.getInstance().publish(ContextChangeEvent.builder().context(executeContext.copy()).build());
    }
}
